package com.example.util;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;

public class ScriptEngineUtil {
    public static String guidRandom() throws IOException, ScriptException, NoSuchMethodException {
        String guid = "";
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("javascript");

        String jsFileName = "guid.js";   // 读取js文件
        String jsFilePath = getJsFilePath(jsFileName);
        System.out.println(jsFilePath);
        FileReader reader = new FileReader(jsFilePath);   // 执行指定脚本
        engine.eval(reader);
        if (engine instanceof Invocable) {
            Invocable invoke = (Invocable) engine;    // 调用merge方法，并传入两个参数
            guid = (String) invoke.invokeFunction("guidRandom");
            System.out.println("guid = " + guid);
        }
        reader.close();
        return guid;
    }

    public static String getJsFilePath(String jsFileName){
        URL url = ScriptEngineUtil.class.getClassLoader().getResource(jsFileName);
        return url.getFile();
    }

    public static void main(String[] args) {
    }
}
